package com.suse.blog.cotronller;

import com.suse.blog.enums.ResultCodeEnum;
import com.suse.blog.model.Result;
import com.suse.blog.model.UserInfo;
import com.suse.blog.service.UserService;
import com.suse.blog.utils.JwtUtils;
import com.suse.blog.utils.SecurityUtils;
import io.jsonwebtoken.lang.Assert;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName,String password) {
        log.info("用户登录，用户名：{}", userName);
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail(ResultCodeEnum.PARAM_INVALID.getCode(), "用户名或密码不能为空");
        }
        //验证账号密码是否正确
        UserInfo userInfo = userService.selectUserInfoByName(userName);
        if(userInfo == null || userInfo.getId() == null) {
            return Result.fail(ResultCodeEnum.USER_NOT_EXIST.getCode(), "用户不存在");
        }
        if(!SecurityUtils.verify(password,userInfo.getPassword())) {
            log.error("密码验证失败！");
            return Result.fail(ResultCodeEnum.PASSWORD_ERROR.getCode(), "密码错误");
        }
//        if(!userInfo.getPassword().equals(password)) {
//            return Result.fail(ResultCodeEnum.PASSWORD_ERROR.getCode(), "密码错误");
//        }
        //账号密码正确
        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id",userInfo.getId());
        cliams.put("name",userInfo.getUserName());

        String jwt = JwtUtils.getJwt(cliams);
        return Result.success(jwt);
   }

   @RequestMapping("/getUserInfo")
   public UserInfo getUserInfo(HttpServletRequest request) {
        String userToken = request.getHeader("user_token_header");
        //从token中获取用户ID
       Integer userId = JwtUtils.getUserIdFromToken(userToken);
       Assert.notNull(userId, "用户未登录");
       UserInfo userInfo = userService.selectUserInfoById(userId);
       return userInfo;
   }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId) {

        Assert.notNull(blogId, "博客ID不能为空");
        UserInfo userInfo = userService.selectAuthorInfoByBlogId(blogId);
        return userInfo;
    }
}
